package com.hzy.fivepalace.wx.service;

import com.hzy.fivepalace.common.util.JacksonUtil;
import com.hzy.fivepalace.common.util.ResponseUtil;
import com.hzy.fivepalace.db.dao.ex.CommonMapperEx;
import com.hzy.fivepalace.db.dao.ex.DtsCartMapperEx;
import com.hzy.fivepalace.db.domain.DtsCart;
import com.hzy.fivepalace.db.domain.DtsGoods;
import com.hzy.fivepalace.db.domain.DtsGoodsProduct;
import com.hzy.fivepalace.db.domain.DtsGoodsSpecification;
import com.hzy.fivepalace.db.service.DtsCartService;
import com.hzy.fivepalace.db.service.DtsGoodsProductService;
import com.hzy.fivepalace.db.service.DtsGoodsService;
import com.hzy.fivepalace.db.service.DtsGoodsSpecificationService;
import com.hzy.fivepalace.db.vo.wx.WxCartVo;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户购物车服务
 */
@Service
public class WxCartService {

    @Autowired
    private DtsGoodsProductService productService;

    @Autowired
    private DtsGoodsSpecificationService specificationService;

    @Autowired
    private DtsGoodsService goodsService;

    @Autowired
    private DtsCartService cartService;

    @Resource
    private DtsCartMapperEx cartMapperEx;

    @Resource
    private Redisson redisson;

    @Resource
    private CommonMapperEx commonMapperEx;

    /**
     * 更改购物车选中状态
     *
     * @param userId
     * @param body
     * @return
     */
    public Object cartCheckStatus(Integer userId, String body) {
        RLock lock = redisson.getLock("wx_cartCheckStatus_" + userId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent();
        }
        lock.lock(30, TimeUnit.SECONDS);

        //购物车ID
        List<Integer> cartIds = JacksonUtil.parseIntegerList(body, "cartIds");
        if (CollectionUtils.isEmpty(cartIds)) {
            lock.unlock();
            return ResponseUtil.badArgument("购物车id为空");
        }
        if (CollectionUtils.isEmpty(cartIds)) {
            lock.unlock();
            return ResponseUtil.badArgument("购物车id为空");
        }
        Boolean checkStatus = JacksonUtil.parseBoolean(body, "checkStatus");
        if (null == checkStatus) {
            lock.unlock();
            return ResponseUtil.badArgument("参数【checkStatus】为空");
        }
        cartService.updateCheck(userId, cartIds, checkStatus);
        lock.unlock();
        return ResponseUtil.ok();
    }


    /**
     * 清空购物车
     *
     * @param userId
     * @return
     */
    public Object emptyCart(Integer userId) {
        RLock lock = redisson.getLock("wx_emptyCart_" + userId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent();
        }
        lock.lock(30, TimeUnit.SECONDS);
        cartService.emptyCart(userId);
        lock.unlock();
        return ResponseUtil.ok("购物车已清空", null);
    }

    /**
     * 购物车数量
     *
     * @param userId
     * @return
     */
    public Object getCartCount(Integer userId) {
        Integer count = 0;
        if (null == userId) {//未登录直接返回0
            return ResponseUtil.ok("ok", count);
        }
        count = cartMapperEx.getUserCartListCount(userId);

        return ResponseUtil.ok(null == count ? 0 : count);
    }

    /**
     * 购物车列表
     *
     * @param userId
     * @return
     */
    public Object getUserCartList(Integer userId) {
        List<WxCartVo> list = cartMapperEx.getUserCartList(userId);
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        //计算已选中的购物车总价
        BigDecimal sumPrice = new BigDecimal("0.00");
        //商品总数
        Integer count = 0;
        //已选数量
        Integer checkCount = 0;
        for (WxCartVo item : list) {
            //已卖完的,和数量小于1的不选择
            if (null == item.getInventory() || item.getInventory().intValue() <= 0 || null == item.getNumber() || item.getNumber().intValue() <= 0|| item.getInventory().intValue()<item.getNumber())  {
                item.setChecked(false);
            }
            if (item.getChecked()) {
                sumPrice = sumPrice.add((item.getNewPrice().multiply(new BigDecimal(item.getNumber().intValue()))));
                count = count + (item.getNumber());
                checkCount = checkCount + 1;
            }
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("list", list);
        result.put("count", count);//商品总数
        result.put("sumPrice", sumPrice);//总价
        result.put("checkCount", checkCount);//已选数量
        return ResponseUtil.ok(result);
    }


    /**
     * 删除购物车
     *
     * @param userId
     * @param body
     * @return
     */
    public Object delCart(Integer userId, String body) {
        RLock lock = redisson.getLock("wx_delCart_" + userId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent();
        }
        lock.lock(30, TimeUnit.SECONDS);
        //购物车ID
        List<Integer> cartIds = JacksonUtil.parseIntegerList(body, "cartIds");
        if (CollectionUtils.isEmpty(cartIds)) {
            lock.unlock();
            return ResponseUtil.badArgument("购物车id为空");
        }
        cartService.deleteByIdAndUserId(cartIds, userId);
        lock.unlock();
        return ResponseUtil.ok("删除成功", null);
    }

    /**
     * 加入、减少购物车
     *
     * @param userId
     * @param body
     * @return
     */
    public Object addOrReduceCart(Integer userId, String body) {
        RLock lock = redisson.getLock("wx_addOrReduceCart_" + userId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent();
        }
        lock.lock(30, TimeUnit.SECONDS);
        //规格ID
        Integer specificationId = JacksonUtil.parseInteger(body, "specificationId");
        //数量
        Integer number = JacksonUtil.parseInteger(body, "number");

        if (null == specificationId || specificationId < 1) {
            lock.unlock();
            return ResponseUtil.badArgument("参数【specificationId】为空");
        }
        if (null == number) {
            lock.unlock();
            return ResponseUtil.badArgument("数量不能为空");
        }

        //子规格的货品id
        Integer childProductxId = null;

        //获取规格信息
        DtsGoodsSpecification specification =specificationService.selectById(specificationId);
        if (null != specification&&specification.getPid().intValue()!=0) {//如果是子级规格，就去查主规格
            //设置子规格的货品id
            childProductxId = specification.getGoodsPoroductId();
            specification=specificationService.selectById(specification.getPid());
        }else if (null != specification && specification.getPid().intValue() == 0) {//如果是主规格，就校验他下面是否有子规格
            if (commonMapperEx.isHaveChildSpecification(specification.getId())) {//如果有子规格，就代表参数specificationId传入错误
                return ResponseUtil.fail("参数【specificationId】错误");
            }
        }
        if (null == specification) {
            lock.unlock();
            return ResponseUtil.badArgument("规格不存在或已下架");
        }

        //货品id
        Integer productId=specification.getGoodsPoroductId();
        DtsGoodsProduct product= productService.selectById(productId);
        if (null == product) {
            lock.unlock();
            return ResponseUtil.badArgument("货品不存在或已下架");
        }

        if (null != childProductxId) {//如果子规格的货品id不为null,就查询子规格的货品信息
            DtsGoodsProduct childProduct = productService.selectById(childProductxId);
            if (null == childProduct) {
                lock.unlock();
                return ResponseUtil.fail("货品不存在或已下架");
            }
        }

        // 商品信息
        DtsGoods goods = goodsService.selectById(product.getGoodsId());
        if (null == goods) {
            lock.unlock();
            return ResponseUtil.badArgument("商品不存在或已下架");
        }

        //查询该货品是否已经存在购物车
        DtsCart userCart = cartService.selectByUserIdAndProductId(userId, productId,specificationId);
        if (null == userCart) {//不存在就新增
            if (number.intValue() < 1) {
                lock.unlock();
                return ResponseUtil.badArgument("数量不能小于1");
            }
            DtsCart cartAdd = new DtsCart();
            cartAdd.setNumber((short) number.intValue());
            cartAdd.setUpdateTime(LocalDateTime.now());
            cartAdd.setAddTime(LocalDateTime.now());
            cartAdd.setUserId(userId);
            cartAdd.setBrandId(goods.getBrandId());
            cartAdd.setGoodsId(goods.getId());
            cartAdd.setGoodsSn(goods.getGoodsSn());
            cartAdd.setSpecifications(specificationId.toString());
            cartAdd.setGoodsName(goods.getName());
            cartAdd.setProductId(null == childProductxId ? productId : childProductxId);
            cartAdd.setPrice(product.getPrice());
            //默认选中
            cartAdd.setChecked(true);
            cartAdd.setPicUrl(product.getUrl());
            cartAdd.setDeleted(false);
            cartService.add(cartAdd);
            lock.unlock();
            return ResponseUtil.ok("已加入购物车", "已加入购物车");
        } else {//存在就修改数量
            DtsCart cartUpd = new DtsCart();
            cartUpd.setId(userCart.getId());
            cartUpd.setUpdateTime(LocalDateTime.now());
            //判断输入的数量是正数还是负数
            if (number < 0) {//负数
                Integer sumCount = userCart.getNumber().intValue() - 1;
                if (sumCount < 1) {//如果小于1就删除掉
                    cartService.deleteById(userCart.getId());
                } else {
                    cartUpd.setNumber((short) sumCount.intValue());
                }
            } else if (number.intValue() == 0) {//等于0
                cartService.deleteById(userCart.getId());
            } else {//正数
                cartUpd.setNumber(number.shortValue());
            }
            cartUpd.setUpdateTime(LocalDateTime.now());
            cartService.updateById(cartUpd);
            lock.unlock();
            return ResponseUtil.ok("操作成功","操作成功");
        }
    }
}
